/**
 *                            License
 * THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS  
 * CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). 
 * THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW.  
 * ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR  
 * COPYRIGHT LAW IS PROHIBITED.
 * 
 * BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND  
 * AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE  
 * MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED 
 * HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.
 * 
 */
package l1j.server.server.model.Instance;

import Limit.BuffDoll.BuffDoll_DollSkill_Load;
import Limit.BuffDoll.BuffDoll_DollSkill_Table;
import Limit.BuffDoll.BuffDoll_Info_Load;
import Limit.BuffDoll.BuffDoll_RunSkill;
import Limit.BuffDoll.BuffDoll_Info_Table;
import l1j.server.server.ActionCodes;
import l1j.server.server.GeneralThreadPool;
import l1j.server.server.IdFactory;
import l1j.server.server.datatables.SprTable;
import l1j.server.server.model.L1Object;
import l1j.server.server.model.L1World;
import l1j.server.server.serverpackets.S_DoActionGFX;
import l1j.server.server.serverpackets.S_DollPack;
import l1j.server.server.serverpackets.S_NPCTalkReturn;
import l1j.server.server.serverpackets.S_OwnCharStatus;
import l1j.server.server.serverpackets.S_SkillIconGFX;
import l1j.server.server.serverpackets.S_SkillSound;
import l1j.server.server.serverpackets.S_SystemMessage;
import l1j.server.server.templates.L1MagicDoll;
import l1j.server.server.templates.L1Npc;
import l1j.server.server.utils.Random;

public class L1DollInstance extends L1NpcInstance {
	private static final long serialVersionUID = 1L;

	public static final int DOLL_TIME = 1800000;
	private int _itemId;
	private int _itemObjId;
	private int run;
	private boolean _isDelete = false;

	// ターゲットがいない場合の処理
	@Override
	public boolean noTarget() {
		if ((_master != null) && !_master.isDead()
				&& (_master.getMapId() == getMapId())) {
			if (getLocation().getTileLineDistance(_master.getLocation()) > 2) {
				int dir = moveDirection(_master.getX(), _master.getY());
				setDirectionMove(dir);
				setSleepTime(calcSleepTime(getPassispeed(), MOVE_SPEED));
			} else if ((getNpcTemplate().get_npcId() >= 902800) && (getNpcTemplate().get_npcId() <= 902809)){
				if(getHierarch() == 1){
					if (getCurrentMp() < 50){
						BuffDoll_Info_Load info = BuffDoll_Info_Table.getInstance().getTemplate(getItemObjId());
						if (info.getAuto_Res()){
							L1PcInstance player = (L1PcInstance) _master;
							if(player.getInventory().checkItem(70213)){
								setCurrentMp(1000);
								player.getInventory().consumeItem(70213, 1);
							} else {
								player.sendPackets(new S_SystemMessage("娃娃艾草不足。"));
								info.setAuto_Res(false);
								BuffDoll_Info_Table updateinfo = BuffDoll_Info_Table.getInstance();
								updateinfo.updateBuffDoll_info(getItemObjId(), info);
							}
						}
					}
					BuffDoll_DollSkill_Load Skill = BuffDoll_DollSkill_Table.getInstance().getTemplate(getItemObjId());
					L1PcInstance player = (L1PcInstance) _master;
	
					int[][] buffinfo = Skill.getSkillInfo();
					for ( int i = 0 ; i < buffinfo.length; i++)
					{
						if (getCurrentMp() >= 50)
						{
							if (buffinfo[i][5] > 0)
							{
								//
								if (buffinfo[i][0] != 0)
								{
									if (!player.hasSkillEffect(buffinfo[i][0] ))
									{
										BuffDoll_RunSkill.getInstance().runSkill(player, buffinfo[i], getItemObjId(), getName(), String.valueOf(getCurrentMp()), String.valueOf(getMaxMp()), getId());
										setCurrentMp(getCurrentMp() - 50);
									}
								}
							}
						}
					}				
				}
				for (L1Object obj : L1World.getInstance().getVisiblePoint(getLocation(), 1)) {
					if (obj instanceof L1PcInstance) {
						L1PcInstance target = (L1PcInstance) obj;
						if ( target.getId() != _master.getId()){
							if ( getX() != _master.getX() || getY() != _master.getY())
								teleportForDoll(_master.getX(), _master.getY(), getHeading());
						}
					}
				}
			}
			else 
			{
				// 魔法娃娃 - 特殊動作
				dollAction();
			}
		} else {
			_isDelete = true;
			deleteDoll();
			return true;
		}
		return false;
	}

	// 時間計測用
	class DollTimer implements Runnable {
		@Override
		public void run() {
			if (_destroyed) { // 既に破棄されていないかチェック
				return;
			}
			deleteDoll();
		}
	}

	public L1DollInstance(L1Npc template, L1PcInstance master, int itemId,
			int itemObjId) {
		super(template);
		setId(IdFactory.getInstance().nextId());

		setItemId(itemId);
		setItemObjId(itemObjId);
		GeneralThreadPool.getInstance().schedule(new DollTimer(), DOLL_TIME);

		setMaster(master);
		setX(master.getX()+2);
		setY(master.getY()+2);
		setMap(master.getMapId());
		setHeading(5);
		setLightSize(template.getLightSize());
		setMoveSpeed(1);
		setBraveSpeed(1);
		
		L1World.getInstance().storeObject(this);
		L1World.getInstance().addVisibleObject(this);
		for (L1PcInstance pc : L1World.getInstance().getRecognizePlayer(this)) {
			onPerceive(pc);
		}
		master.addDoll(this);
		if (!isAiRunning()) {
			startAI();
		}
		if (L1MagicDoll.isHpRegeneration(_master)) {
			master.startHpRegenerationByDoll();
		}
		if (L1MagicDoll.isMpRegeneration(_master)) {
			master.startMpRegenerationByDoll();
		}
		if (L1MagicDoll.isItemMake(_master)) {
			master.startItemMakeByDoll();
		}
		if ( itemId >= 60100 && itemId <= 60119){
			BuffDoll_Info_Load info = BuffDoll_Info_Table.getInstance().getTemplate(getItemObjId());
			setCurrentMp(info.getMP());
		}
	}

	public void deleteDoll() {
		broadcastPacket(new S_SkillSound(getId(), 5936));
		if (_master != null && _isDelete) {
			L1PcInstance pc = (L1PcInstance) _master;
			pc.sendPackets(new S_SkillIconGFX(56, 0));
			pc.sendPackets(new S_OwnCharStatus(pc));
		}
		if (L1MagicDoll.isHpRegeneration(_master)) {
			((L1PcInstance) _master).stopHpRegenerationByDoll();
		}
		if (L1MagicDoll.isMpRegeneration(_master)) {
			((L1PcInstance) _master).stopMpRegenerationByDoll();
		}
		if (L1MagicDoll.isItemMake(_master)) {
			((L1PcInstance) _master).stopItemMakeByDoll();
		}
		_master.getDollList().remove(getId());
		deleteMe();
		if (getItemId() >= 60100 && getItemId() <= 60119){
			BuffDoll_Info_Load info = BuffDoll_Info_Table.getInstance().getTemplate(getItemObjId());
			info.setMP(getCurrentMp());
			BuffDoll_Info_Table updateinfo = BuffDoll_Info_Table.getInstance();
			updateinfo.updateBuffDoll_info(getItemObjId(), info);
		}
	}

	@Override
	public void onPerceive(L1PcInstance perceivedFrom) {
		// 判斷旅館內是否使用相同鑰匙
		if (perceivedFrom.getMapId() >= 16384 && perceivedFrom.getMapId() <= 25088 // 旅館內判斷
				&& perceivedFrom.getInnKeyId() != _master.getInnKeyId()) {
			return;
		}
		perceivedFrom.addKnownObject(this);
		perceivedFrom.sendPackets(new S_DollPack(this));
	}

	@Override
	public void onItemUse() {
	}

	@Override
	public void onGetItem(L1ItemInstance item) {
	}

	public int getItemObjId() {
		return _itemObjId;
	}

	public void setItemObjId(int i) {
		_itemObjId = i;
	}
	//buff娃娃
	public void onTalkAction(L1PcInstance player) {
		if (isDead()) {
			return;
		}
		if (_master.equals(player) &&
			((getNpcTemplate().get_npcId() >= 902800) && (getNpcTemplate().get_npcId() <= 902809))) {
			BuffDoll_Info_Load info = BuffDoll_Info_Table.getInstance().getTemplate(getItemObjId());
			BuffDoll_DollSkill_Table updateSkill = BuffDoll_DollSkill_Table.getInstance();
			updateSkill.loadDollSkill_Info(getItemObjId());

			String status = "";
			String heal = String.valueOf(player.getHierarch() * 10);
			if (getHierarch() == 1) {
				status = "啟動";
			} else {
				status = "暫停";
			}
			String[] htmldata = new String[29];
			htmldata = info.getInfo(getName(), String.valueOf(getCurrentMp()), String.valueOf(getMaxMp()), status, heal);
			String mdhtmlid = "BuffD_FP";
			player.sendPackets(new S_NPCTalkReturn(getId(), mdhtmlid, htmldata));

		}
	}
		
	//buff娃娃回魔相關
	public void onFinalAction(L1PcInstance player, String action) {
	}	

	@Override
	public void setCurrentMp(int i) {
		int currentMp = i;
		if (currentMp >= getMaxMp()) {
			currentMp = getMaxMp();
		}
		setCurrentMpDirect(currentMp);
		if (getMaxMp() > getCurrentMp()) {
			startDollMpRegeneration(getItemObjId());
		}
	}
	//buff娃娃回魔相關end  
		
	public int getItemId() {
		return _itemId;
	}

	public void setItemId(int i) {
		_itemId = i;
	}

	// 表情動作
	private void dollAction() {
		run = Random.nextInt(100) + 1;
		if (run <= 10) {
			int actionCode = ActionCodes.ACTION_Aggress; // 67
			if (run <= 5) 
				actionCode = ActionCodes.ACTION_Think; // 66

			broadcastPacket(new S_DoActionGFX(getId(), actionCode));
			setSleepTime(calcSleepTime(SprTable.getInstance().getSprSpeed(getTempCharGfx(),
							actionCode), MOVE_SPEED)); //
		}
	}
}
